﻿namespace StatlightTfsBuildIntegration.TfsServiceUtil
{
	using System;
	using System.Security.Principal;

	public static class IdentityManagement
	{
		public static Guid ReadCurrentUsersIdentity()
		{
			Console.WriteLine("Reading users identity...");
			string url = "http://nlses010:8080/tfs2010/Services/v3.0/IdentityManagementService.asmx";
			using (var client = ServiceClientFactory.CreateIdentityManagementWebServiceSoapClient())
			{
				var currentUser = WindowsIdentity.GetCurrent();

				if (currentUser == null)
				{
					throw new InvalidOperationException("Could not find current Windows user.");
				}

				var result = client.ReadIdentities(0, new[] { currentUser.Name }, 0, 0);

				if ((result == null) || (result.Length != 1) || (result[0].Length != 1))
				{
					throw new InvalidOperationException(string.Format("Could not find user {0} in TFS.", currentUser.Name));
				}

				return result[0][0].TeamFoundationId;
			}
		}
	}
}
